# -*- coding: utf-8 -*-
import os
import h5py
import numpy as np

from resnet50 import ResNet
from flask import jsonify, request




def get_imlist(path):
    return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')]

# 拆分数据，每100条启动一个线程
def splitData():
    database = request.json.get("path").strip()
    index = request.json.get("index").strip()
    img_list = get_imlist(database)
    return preloadingPic(img_list, index)

    # val = [img_list[i: i + 10] for i in range(0, len(img_list) - 10, 10)]
    # print(val)
    #
    # for i in val:
    #     index1 = index
    #     print(i, end=' ')
    #     sing_process = threading.Thread(target=preloadingPic, args=(i, index1))
    #     sing_process.start()
    #     print(i, end=' ')


    # if len(img_list)>100:
    #     sing_process = threading.Thread(target=preloadingPic,args=(img_list,))
    #     sing_process.start()

# 对图片数据进行特征提取
def preloadingPic(img_list,index):
    # database = request.json.get("path").strip()
    # index = request.json.get("index").strip()

    # database = r'D:\pythonProject5\flower_roses'
    # index = 'vgg_featureCNN.h5'
    # img_list = get_imlist(database)

    print("feature extraction starts(特征提取开始)")

    feats = []
    names = []

    model = ResNet()
    for i, img_path in enumerate(img_list):
        norm_feat = model.resnet_extract_feat(img_path)  # 修改此处改变提取特征的网络
        img_name = os.path.split(img_path)[1]
        # print("norm_feat is : "+norm_feat)
        feats.append(norm_feat)
        names.append(img_name)
        # print("从第 %d 张图像中提取特征，共 %d 张图像" % ((i + 1), len(img_list)))
        # print("extracting feature from image No. %d , %d images in total" % ((i + 1), len(img_list)))

    feats = np.array(feats)

    output = index
    print("writing feature extraction results(写入特征提取结果) ...")

    h5f = h5py.File(output, 'w')
    h5f.create_dataset('dataset_1', data=feats)
    # h5f.create_dataset('dataset_2', data = names)
    h5f.create_dataset('dataset_2', data=np.string_(names))
    h5f.close()
    return jsonify(
        {"code": 2000, "msg": "特征提取成功！"}
    )